package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.bean.BeanUtils;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.DeviceReportDataVo;
import com.zzyl.serve.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

/**
 * deviceService业务层处理
 *
 * @author MWJ
 * @date 2025-08-22
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private IoTDAClient client;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 查询device
     *
     * @param id device主键
     * @return device
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询device列表
     *
     * @param device device
     * @return device
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增device
     *
     * @param device device
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改device
     *
     * @param device device
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除device
     *
     * @param ids 需要删除的device主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除device信息
     *
     * @param id device主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    @Override
    public void syncProductList() {
        //获取全部产品并设置到缓存中
        ListProductsRequest request = new ListProductsRequest();
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("从华为云同步产品列表失败");
        }
        List<ProductSummary> products = response.getProducts();
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCTS_KEY, JSONUtil.toJsonStr(products));
    }

    @Override
    public List<ProductVo> allProducts() {
        String allProducts = (String) redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCTS_KEY);
        if (StringUtils.isEmpty(allProducts)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(allProducts, ProductVo.class);
    }

    @Override
    public void registerDevice(DeviceDto dto) {
        //前置校验
        //设备标识码是否已存在
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getNodeId, dto.getNodeId());
        Device device = deviceMapper.selectOne(wrapper);
        if (device != null) {
            throw new BaseException("该设备标识码已存在");
        }
        //设备名称是否已存在
        wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getDeviceName, dto.getDeviceName());
        device = deviceMapper.selectOne(wrapper);
        if (device != null) {
            throw new BaseException("该设备名称已存在");
        }
        //同一位置是否已绑定同类型设备
        wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getBindingLocation, dto.getBindingLocation())
                .eq(Device::getLocationType, dto.getLocationType())
                .eq(dto.getPhysicalLocationType() != null, Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                .eq(Device::getProductKey, dto.getProductKey());
        device = deviceMapper.selectOne(wrapper);
        if (device != null) {
            throw new BaseException("该位置已绑定该设备");
        }
        //到华为云注册该设备
        //设置注册设备信息
        AddDevice body = new AddDevice();
        body.setProductId(dto.getProductKey());
        body.setNodeId(dto.getNodeId());
        body.setDeviceName(dto.getDeviceName());
        //随机生成密钥
        AuthInfo authInfo = new AuthInfo();
        String secret = UUID.randomUUID().toString(true);
        authInfo.withSecret(secret);
        body.setAuthInfo(authInfo);
        AddDeviceRequest request = new AddDeviceRequest();
        request.withBody(body);
        AddDeviceResponse response = client.addDevice(request);

        //将设备保存到数据库
        device = new Device();
        BeanUtils.copyProperties(dto, device);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        device.setDeviceDescription(dto.getDeviceDescription());
        save(device);
    }

    @Override
    public DeviceDetailVo detail(String iotId) {
        DeviceDetailVo vo = new DeviceDetailVo();
        //从数据库查询
        LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId);
        Device device = deviceMapper.selectOne(wrapper);
        if (device == null) {
            return null;
        }
        BeanUtils.copyProperties(device, vo);
        //类型转换
        vo.setBindingLocation(Long.parseLong(device.getBindingLocation()));
        vo.setCreateTime(device.getCreateTime().toInstant().atZone(ZoneId.of("Asia/Shanghai")).toLocalDateTime());
        //从华为云获取设备详情
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = client.showDevice(request);
        //设置到vo
        vo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTime.parse(activeTimeStr, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"));
            //时区转换
            activeTime = activeTime.atZone(ZoneId.of("UTC")).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
            vo.setActiveTime(activeTime);
        }
        return vo;
    }

    @Override
    public List<DeviceReportDataVo> queryDeviceProperties(String iotId) {
        //从华为云获取设备数据然后封装返回，获取数据参考设备影子SDK示例
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);
        //如果response中的状态码不为200，抛自定义异常
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("从云端获取设备数据失败");
        }
        //获取上报
        if (CollectionUtils.isEmpty(response.getShadow())) {
            throw new BaseException("该设备未被激活");
        }
        DeviceShadowProperties reported = response.getShadow().get(0).getReported();
        //获取上报时间，转为LocalDateTime对象并转换时区为东八区
        String eventTimeStr = reported.getEventTime();
        LocalDateTime eventTime = LocalDateTime.parse(eventTimeStr, DateTimeFormatter.ofPattern("yyyyMMdd'T'HHmmss'Z'"))
                .atZone(ZoneId.of("UTC"))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();
        //获取上报属性及其数据的Map
        Map<String, Object> properties = (Map<String, Object>) reported.getProperties();
        //遍历map，封装为List<DeviceReportDataVo>
        List<DeviceReportDataVo> list = new ArrayList<>();
        properties.forEach((k, v) -> {
            DeviceReportDataVo vo = new DeviceReportDataVo();
            vo.setFunctionId(k);
            vo.setValue(v);
            vo.setEventTime(eventTime);
            list.add(vo);
        });
        return list;
    }

    @Override
    public void editDevice(DeviceDto dto) {
        //从数据库中查到iotId
        Device device = deviceMapper.selectDeviceById(dto.getId());
        //修改华为云中的设备
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        request.withDeviceId(device.getIotId());
        UpdateDevice body = new UpdateDevice();
        AuthInfoWithoutSecret authInfobody = new AuthInfoWithoutSecret();
        authInfobody.withSecureAccess(true);
        body.withAuthInfo(authInfobody);
        body.withDeviceName(dto.getDeviceName());
        request.withBody(body);
        UpdateDeviceResponse response = client.updateDevice(request);
        //如果响应不为200，抛自定义异常
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("云端修改设备名失败");
        }
        //修改数据库中的设备
        //当数据库中字段不为null,而传入值为null时，无法覆盖，会导致无法修改，数据错乱
        //前端发送的请求与接口文档不符，当设备为随身设备时，physical_location_type 与device_description未按要求传输，直接修改前端会更便捷
        BeanUtils.copyProperties(dto, device);
        updateDevice(device);
    }

    @Override
    public void deleteDevice(String iotId) {
        //从华为云中删除设备
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        //云端删除成功后返回的状态码是204，无响应内容
        DeleteDeviceResponse response = client.deleteDevice(request);
        // 判断是否为2xx成功状态码
        if (response.getHttpStatusCode() / 100 == 2) {
            //从数据库中删除设备
            LambdaQueryWrapper<Device> wrapper = Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId);
            remove(wrapper);
        } else {
            // 处理删除失败的情况
            throw new BaseException("云端删除设备失败，HTTP状态码: " + response.getHttpStatusCode());
        }
    }

    @Override
    public List<ServiceCapability> queryProductModelProperty(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.setProductId(productKey);
        ShowProductResponse response = client.showProduct(request);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("从华为云获取产品信息失败");
        }
        return response.getServiceCapabilities();
    }
}
